package com.framework2.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程池工具类
 *
 * @author YobertJomi
 * className ThreadPoolUtil
 * created at  2017/3/29  11:50
 */

public class ThreadPoolUtil {

    private static volatile ThreadPoolUtil instance;
    /**
     * 每次只执行一个任务的线程池
     */
    private static ExecutorService singleTaskExecutor = null;
    /**
     * 每次执行限定个数个任务的线程池
     */
    private static ExecutorService limitedTaskExecutor = null;

    public static ThreadPoolUtil getInstance() {
        if (instance == null) {
            synchronized (ThreadPoolUtil.class) {
                if (instance == null) {
                    instance = new ThreadPoolUtil();
                }
            }
        }
        return instance;
    }

    /**
     * 每次只执行一个线程任务的线程池
     * 限制最大线程数的线程池 一个
     * Executors.newSingleThreadExecutor()
     */
    public ExecutorService getInstanceSingleTaskExecutor() {
        if (null == singleTaskExecutor) {
            synchronized (ThreadPoolUtil.class) {
                if (null == singleTaskExecutor) {
                    singleTaskExecutor = Executors.newSingleThreadExecutor();// 每次只执行一个线程任务的线程池
                }
            }
        }
        return singleTaskExecutor;
    }

    /**
     * 每次执行限定个数个任务的线程池（不传默认为3个）
     * 限制最大线程数的线程池 nThreads
     * Executors.newFixedThreadPool(3)
     */
    public ExecutorService getInstanceLimitedTaskExecutor(int nThreads) {
        if (null == limitedTaskExecutor) {
            synchronized (ThreadPoolUtil.class) {
                if (null == limitedTaskExecutor) {
                    limitedTaskExecutor = Executors.newFixedThreadPool(nThreads);// 限制线程池大小为3的线程池
                }
            }
        }
        return limitedTaskExecutor;
    }
}
